import { Engine } from "../engine";
import { Util } from "../../utils/util";
import { DocBase } from "../common/docBase";
import { DocType, CommonOrderStatus, ProgressState } from "../common/docDefinition";
import { TargetObject, TargetObjectType } from "../targetOrg/targetObject";
import { PendingReceiveOrderRelation } from "./receiveOrder";
import { PendingReceiveFundSource, PendingFundNumType } from "../common/fundDefinition";

/// 应收单据过滤条件
export class PendingReceiveOrderFilter {
    /// 往来单位ID
    targetObjId = null;

    // 往来单位名称
    targetObjName = null;

    /// 单据来源 PendingReceiveFundSource
    fundSource = null;

    /// 收款金额类型 PendingFundNumType
    fundNumType = null;

    /// 进度状态 ProgressState.code
    igProgressStateCode = null;   // 

    /// 门店过滤
    storeId = null;

    constructor({ targetObjId = null, fundSource = null, storeId = null, targetObjName = null }) {
        this.targetObjId = targetObjId;
        this.fundSource = fundSource;
        this.storeId = storeId ?? Engine.profile?.filterStore?.id;
        this.targetObjName = targetObjName;

       // console.log("PendingPaymentOrderFilter", this);
    }

    clear() {
        this.targetObjId = null;
        this.fundSource = null;
        this.targetObjName = null;
    }

    static clone(filter) {
        const cloned = new PendingReceiveOrderFilter({
            targetObjId: filter.targetObjId,
            fundSource: filter.fundSource,
            storeId: filter.storeId,
            targetObjName: filter.targetObjName
        });
        cloned.fundNumType = filter.fundNumType;
        cloned.igProgressState = filter.igProgressState;
        return cloned;
    }
    toJson() {
        const ret = {};
        if (this.targetObjId != null) {
            ret["objId"] = this.targetObjId;
        }

        if (this.targetObjName != null) {
            ret["ign_objName"] = this.targetObjName;
        }

        if (this.fundSource != null && this.fundSource != PendingReceiveFundSource.Unknown) {
            ret["b_dataSource"] = this.fundSource.code;
        }

        if (this.fundNumType != null) {
            ret["ign_fundNumType"] = this.fundNumType.code;
        }

        if (this.igProgressStateCode == null) {
            ret["b_neq_billStatus"] = ProgressState.AllDone.code;
        } else {
            ret["b_ign_billStatus"] = this.igProgressStateCode;
        }

        // 门店过滤
        if (this.storeId != null) {
            ret["storeId"] = this.storeId;
        }

       // console.log("PendingPaymentOrderFilter toJson", ret);
        return ret;
    }
}

/// 应收单据
export class PendingReceiveOrder extends DocBase {
    constructor({
        // Required params
        targetObject,   // 往来单位 TargetObject
        progressState,  // 支付状态 ProgressState
        totalMount,     // 总金额 
        receiveRelationOrderList,  // 关联的收款单据列表 List<PendingReceiveOrder>
        dataSource = PendingReceiveFundSource.NormalOrder, // PendingReceiveFundSource 应收单据类型


        hexiaoAmount = 0,   // 已经核销金额
        payingMount = 0,  //处理中金额
        pendingPayMount = null,  // 待结算金额
        payedMount = 0,  // 已结算金额

        // super param
        id,
        storeId,
        storeName,
        remark = "",
        operator = "",
        operatorId = "",
        docMaker = "",
        status = CommonOrderStatus.Passed,
        title = "",
        docCode = "",
        parentDocType = null,
        parentDocCode = "",
        parentDocTitle = "",
        sourceDocType = null,
        sourceDocCode = "",
        sourceDocTitle = "",
        recordDate = null,

        initWithCalcRecRelation = false  // 初始化数据类型
    }) {


        super({
            id: id,
            storeId: storeId,
            storeName: storeName,
            title: title,
            docCode: docCode,
            status: status,
            docType: DocType.YSKD,
            parentDocType: parentDocType,
            parentDocCode: parentDocCode,
            parentDocTitle: parentDocTitle,
            sourceDocCode: sourceDocCode,
            sourceDocType: sourceDocType,
            sourceDocTitle: sourceDocTitle,
            recordDateTime: recordDate,
            operator: operator,
            operatorId: operatorId,
            docMaker: docMaker,
            remark: remark
        });

        this.targetObject = targetObject;
        this.progressState = progressState;
        this._totalMount = totalMount;
        /// 付款记录  List<PendingReceiveOrderRelation>
        this._receiveRelationOrderList = receiveRelationOrderList || [];

        /// 应收单据类型
        this.dataSource = dataSource;
        /// 待结算金额
        /// 总金额 - 所有付款单核销金额
        this._pendingPayMount = pendingPayMount ?? ( totalMount - hexiaoAmount );  // 注意本次可能会有问题
        /// 处理中金额
        /// 所有待审核付款的核销金额总和
        this._payingMount = payingMount;
        /// 已结算金额
        /// 所有已审核付款的核销金额总和
        this._payedMount = payedMount;

        if (initWithCalcRecRelation) {
            this.calculateMount();
        }
    }

    static empty({ storeId = null, storeName = null } = {}) {
        return new PendingReceiveOrder({
            targetObject: new TargetObject({ objType: TargetObjectType.Unknown }),
            progressState: ProgressState.None,
            totalMount: 0,
            receiveRelationOrderList: [],
            pendingPayMount:0,
            payingMount: 0,
            payedMount:0,
            id: "",
            storeId: storeId,
            storeName: storeName,
            dataSource: PendingReceiveFundSource.NormalOrder,
            initWithCalcRecRelation: false
        });
    }

    /// 总金额 double
    get totalMount() { return this._totalMount; }

    /// 已结算金额 double
    get payedMount() { return this._payedMount; }

    /// 处理中金额 double
    get payingMount() { return this._payingMount; }

    /// 待结算金额 总金额 - 所有付款单核销金额 double
    get pendingPayMount() { return this._pendingPayMount; }

    /// 关联收款单列表 Iterable<PendingReceiveOrderRelation>
    get receiveRelationList() {
        return [...this._receiveRelationOrderList];
    }

    /// 是否包含收款单据(除开业务单据直接收款)
    get hasUserReceiveOrder() {
        return this._receiveRelationOrderList.some(
            element => element.receiveOrder.triggerDocCode.length === 0
        );
    }

    /// 计算金额
    calculateMount() {
        this._payedMount = 0;
        this._payingMount = 0;

        for (const element of this._receiveRelationOrderList) {
            const value = element.hexiaoAmount;
            if (element.receiveOrder.status.code === CommonOrderStatus.Passed.code) {
                this._payedMount += value;
            } else {
                this._payingMount += value;
            }
        }

        this._pendingPayMount = this._totalMount - this._payedMount - this._payingMount;
    }

    /// 更新支付列表 order: List<PendingReceiveOrderRelation>
    updateReceiveList(orders) {
        this._receiveRelationOrderList = orders;
        this.calculateMount();
    }

    /// 解析服务器数据
  /// overprice是包含了已审核金额+未审核金额
  /// payment_price是总金额，overprice是所有已经产生付款单的金额，preprice是未审核的金额
    static fromJson(json, { parentDocType = null, sourceDocType = null } = {}) {

        let baseOrder = DocBase.fromJson(json, DocType.YSKD, { parentDocType, sourceDocType });

        const instance = new PendingReceiveOrder({
            targetObject: json.objId == null
                ? (new TargetObject({ objType: TargetObjectType.Unknown }))
                : (new TargetObject({
                    id: Util.jsonToString(json.objId),
                    name: Util.jsonToString(json.objName),
                    objType: TargetObjectType.Unknown
                })),
            progressState: Util.jsonToPorgressState(json.billStatus, ProgressState.None),
            totalMount: Util.jsonToDouble(json.receiptPrice),
            receiveRelationOrderList: [],
            pendingPayMount : 0, // 构造函数中计算
            payingMount:  Util.jsonToDouble(json.prePrice),
            payedMount: 0,
            dataSource: Util.jsonToPendingReceiveFundSource(json.dataSource),
            
            // 初始化方式, 不进行计算
            initWithCalcRecRelation: false
        });

        Object.assign(instance, baseOrder);

        // Overprice是所有已经产生付款单的金额
        const overPrice = json.overPrice || 0;
        instance._payedMount = overPrice - instance._payingMount;        
           // 计算待支付金额
        instance._pendingPayMount = instance._totalMount - instance._payedMount - instance._payingMount;

        const paymentJsonList = json.payments || [];
        for (const element of paymentJsonList) {
            instance._receiveRelationOrderList.push(
                PendingReceiveOrderRelation.fromJsonForPendingReceiveOrder(element, instance)
            );
        }

        //console.log("pendingReceiveOrder.fromJson:",instance);

        return instance;
    }

    _$PendingReceiveOrderToPrintJson(instance) {
        const ret = super.toJson();
        ret.totalMount = instance.totalMount;
        ret.payedMount = instance.payedMount;
        ret.pendingPayMount = instance.pendingPayMount;
        ret.progressStatus = instance.progressState;
        ret.targetObject = instance.targetObject.toPrintInfoJson();

        ret.details = [];
        for (const element of instance.receiveRelationList) {
            ret.details.push(element.toPrintInfoJson());
        }
        return ret;
    }

    /// 打印信息json 调试用
    toPrintInfoJson() {
        return this._$PendingReceiveOrderToPrintJson(this);
    }
}